'use client'

import { useChatStore } from '@/store/chat'
import request from '@/utils/frontend/request'
import { Avatar, Badge, Dropdown, Input, List, message } from 'antd'
import type { MenuProps } from 'antd'
import { useParams, useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'

export interface Chat {
	id: number
	unreadCount: number
	updatedAt: string
	contact: User
	lastMessage?: string
}

export default function ChatLayout({ children }: { children: React.ReactNode }) {
	const params = useParams()
	const router = useRouter()
	const [messageApi, contextHolder] = message.useMessage()
	const { chatList, activeChat, setChatList, setActiveChat } = useChatStore()

	// 添加置顶状态
	const [pinnedChats, setPinnedChats] = useState<Set<number>>(new Set())

	useEffect(() => {
		fetchChats()
	}, [])

	// 在组件卸载时清除聊天状态
	useEffect(() => {
		return () => {
			setActiveChat(null)
		}
	}, [])

	// 获取聊天列表
	const fetchChats = async () => {
		try {
			const { success, data } = (await request.get('/chat')) as ApiResponse

			if (success) {
				setChatList(data)
				if (params.id) {
					const currentChat = data.find((chat: Chat) => chat.id === Number(params.id))
					if (currentChat) {
						setActiveChat(currentChat)
					}
				}
			}
		} catch (error) {
			messageApi.error('获取聊天列表失败')
		}
	}

	// 右键菜单项
	const getMenuItems = (chatId: number): MenuProps['items'] => [
		{
			key: 'pin',
			label: pinnedChats.has(chatId) ? '取消置顶' : '置顶',
			onClick: () => {
				const newPinnedChats = new Set(pinnedChats)
				if (pinnedChats.has(chatId)) {
					newPinnedChats.delete(chatId)
				} else {
					newPinnedChats.add(chatId)
				}
				setPinnedChats(newPinnedChats)
			},
		},
		{
			key: 'delete',
			label: '删除',
			danger: true,
			onClick: async () => {
				try {
					await request.delete(`/chat/${chatId}`)
					// 从列表中移除
					setChatList(chatList.filter((chat) => chat.id !== chatId))
					// 如果当前选中的是被删除的聊天，则清除选中状态
					if (activeChat?.id === chatId) {
						setActiveChat(null)
						router.push('/im-system/chat')
					}
					messageApi.success('删除成功')
				} catch (error) {
					messageApi.error('删除失败')
				}
			},
		},
	]

	// 对聊天列表进行排序：置顶的在前面
	const sortedChatList = [...chatList].sort((a, b) => {
		if (pinnedChats.has(a.id) && !pinnedChats.has(b.id)) return -1
		if (!pinnedChats.has(a.id) && pinnedChats.has(b.id)) return 1
		return 0
	})

	return (
		<div className="flex h-full">
			{contextHolder}
			{/* 联系人列表 */}
			<div className="w-72 bg-white border-l border-r border-gray-200">
				<div className="p-4 border-b">
					<Input.Search placeholder="搜索联系人" />
				</div>
				<div className="h-[calc(100%-73px)] overflow-y-auto">
					<List
						dataSource={sortedChatList}
						renderItem={(chat) => (
							<Dropdown menu={{ items: getMenuItems(chat.id) }} trigger={['contextMenu']}>
								<List.Item
									className={`cursor-pointer hover:bg-gray-50 ${
										activeChat?.id === chat.id ? 'bg-gray-100' : ''
									}`}
									onClick={async () => {
										setActiveChat(chat)
										if (chat.unreadCount > 0) {
											await request.post(`/chat/${chat.id}/read`)
											const updatedChat = {
												...chat,
												unreadCount: 0,
											}
											setChatList(chatList.map((c) => (c.id === chat.id ? updatedChat : c)))
										}
										router.push(`/im-system/chat/${chat.id}`)
									}}
								>
									<List.Item.Meta
										avatar={
											<Badge dot={chat.contact.status === 'online'} offset={[-8, 8]} color="green">
												<Avatar src={chat.contact.avatar} size={48} />
											</Badge>
										}
										title={
											<div className="flex items-center">
												<span>{chat.contact.nickname}</span>
												{pinnedChats.has(chat.id) && (
													<Badge
														count="置顶"
														style={{ backgroundColor: '#52c41a' }}
														className="ml-2"
													/>
												)}
											</div>
										}
										description={chat.lastMessage}
									/>
									{chat.unreadCount ? (
										<Badge count={chat.unreadCount} style={{ backgroundColor: '#52c41a' }} />
									) : null}
								</List.Item>
							</Dropdown>
						)}
					/>
				</div>
			</div>

			{/* 聊天区域 */}
			<div className="flex-1 flex flex-col bg-gray-50">{children}</div>
		</div>
	)
}
